﻿/*  
 *  IIS LogFile Analyser, Copyright (C) 2013. http://www.iis-analyser.com
 *  --
 *  This program is free software, provided "AS IS" WITHOUT ANY WARRANTY; without even the implied warranty of 
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE
 * 
 *  File Author: Ian Quigley,    2013-02-23
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DataStore;
using AppLogic;
using System.Data;

namespace LogProcess
{
    public class SQLCommand : ICommandAction
    {
        public string Process( CommandParameters parameters )
        {
            var store = new Store( (string)parameters["DatabaseFile"] );

            DataSet ds = store.SQL( (string)parameters["SQL"] );
            if (ds.Tables.Count == 0)
                return null;

            if (ds.Tables.Count == 1)
            {
                ConsoleWriteTable( ds.Tables[0] );
            }
            else
            {
                foreach (DataTable table in ds.Tables)
                {
                    Console.WriteLine( table.TableName );
                    ConsoleWriteTable( table );
                }
            }

            return null;
        }

        private void ConsoleWriteTable( DataTable table )
        {
            foreach (DataColumn col in table.Columns)
            {
                Console.Write( col.Caption + ", " );
            }
            Console.WriteLine( "" );


            foreach (DataRow row in table.Rows)
            {
                foreach (DataColumn col in table.Columns)
                    Console.Write( row[col] + ", " );

                Console.WriteLine( "" );
            }
        }

        public string Description()
        {
            return "Execute arbitary SQL.";
        }

        public List<CommandParameter> Parameters
        {
            get 
            {
                return new List<CommandParameter>() 
                    {
                        new CommandParameter() { Name = "DatabaseFile", Type= CommandParameterType.String},
                        new CommandParameter() { Name = "SQL", Type= CommandParameterType.String}
                    };
            }
        }
    }
}
